import 'dart:math';

import 'package:audio_wave/audio_wave.dart';
import 'package:flutter/material.dart';
import 'package:iconify_flutter/iconify_flutter.dart';
import 'package:iconify_flutter/icons/ic.dart';
import 'package:just_audio/just_audio.dart';

import '../../../widgets/containers/message_container.dart';
import '../../../../utils/author_details_location.dart';
import '../../../../utils/chat_theme.dart';
import '../../../widgets/containers/text_container.dart';
import '../../user.dart';
import 'message.dart';

class AudioMessage extends Message {
  String voiceUrl = "";
  int voiceLen = 0;

  AudioMessage({
    required super.author,
    required super.time,
    this.voiceUrl = "",
    this.voiceLen = 0,
    super.stage,
  });

  @override
  Widget builder(
      BuildContext ctx,
      bool showUserAvatar,
      bool showMessageStatus,
      bool showUsername,
      User loggedInUser,
      ChatTheme theme,
      AuthorDetailsLocation authorDetailsLocation) {
    Widget returnValue = GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        showDialog(
          context: ctx,
          builder: (BuildContext context) {
            return AudioPlayerDialog(voiceUrl);
          },
        );
      },
      child: Padding(
        padding: const EdgeInsets.all(15),
        child: Row(
          children: [
            Iconify(
              Ic.round_play_arrow,
              color: theme.primaryColor,
            ),
            const SizedBox(
              width: 10,
            ),
            Expanded(
              child: AudioWave(
                height: 30,
                width: 160,
                spacing: 5,
                alignment: 'center',
                animationLoop: 1,
                beatRate: const Duration(milliseconds: 50),
                bars: [
                  AudioWaveBar(heightFactor: Random().nextDouble(), color: theme.audioWaveColor),
                  AudioWaveBar(heightFactor: Random().nextDouble(), color: theme.audioWaveColor),
                  AudioWaveBar(heightFactor: Random().nextDouble(), color: theme.audioWaveColor),
                  AudioWaveBar(heightFactor: Random().nextDouble(), color: theme.audioWaveColor),
                  AudioWaveBar(heightFactor: Random().nextDouble(), color: theme.audioWaveColor),
                  AudioWaveBar(heightFactor: Random().nextDouble(), color: theme.audioWaveColor),
                  AudioWaveBar(heightFactor: Random().nextDouble(), color: theme.audioWaveColor),
                  AudioWaveBar(heightFactor: Random().nextDouble(), color: theme.audioWaveColor),
                  AudioWaveBar(heightFactor: Random().nextDouble(), color: theme.audioWaveColor),
                  AudioWaveBar(heightFactor: Random().nextDouble(), color: theme.audioWaveColor),
                  AudioWaveBar(heightFactor: Random().nextDouble(), color: theme.audioWaveColor),
                  AudioWaveBar(heightFactor: Random().nextDouble(), color: theme.audioWaveColor),
                  AudioWaveBar(heightFactor: Random().nextDouble(), color: theme.audioWaveColor),
                  AudioWaveBar(heightFactor: Random().nextDouble(), color: theme.audioWaveColor),
                  AudioWaveBar(heightFactor: Random().nextDouble(), color: theme.audioWaveColor),
                  AudioWaveBar(heightFactor: Random().nextDouble(), color: theme.audioWaveColor),
                  AudioWaveBar(heightFactor: Random().nextDouble(), color: theme.audioWaveColor),
                  AudioWaveBar(heightFactor: Random().nextDouble(), color: theme.audioWaveColor),
                  AudioWaveBar(heightFactor: Random().nextDouble(), color: theme.audioWaveColor),
                  AudioWaveBar(heightFactor: Random().nextDouble(), color: theme.audioWaveColor),
                ],
              ),
            ),
            const SizedBox(
              width: 8,
            ),
            TextContainer(
              text: "$voiceLen“",
              style: author.id == loggedInUser.id
                  ? theme.outwardMessageTextStyle
                  : theme.inwardMessageTextStyle,
              linkStyle: theme.urlTextStyle,
            )
          ],
        ),
      ),
    );
    return MessageContainer(
      parentContext: ctx,
      message: this,
      theme: theme,
      showUserAvatar: showUserAvatar,
      showMessageStatus: showMessageStatus,
      showUsername: showUsername,
      user: loggedInUser,
      detailsLocation: authorDetailsLocation,
      child: returnValue,
    );
  }
}

class AudioPlayerDialog extends StatefulWidget {
  String voiceUrl = "";

  AudioPlayerDialog(this.voiceUrl);

  @override
  _AudioPlayerDialogState createState() => _AudioPlayerDialogState();
}

class _AudioPlayerDialogState extends State<AudioPlayerDialog>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  bool _isPlaying = false;
  final player = AudioPlayer();

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 300),
    );
    player.playerStateStream.listen((state) {
      if(state.processingState==ProcessingState.completed){
        setState(() {
          _isPlaying = !_isPlaying;
        });
        _animationController.reverse();
      }
    });
  }

  @override
  void dispose() {
    _animationController.dispose();
    player.stop();
    super.dispose();
  }

  void _togglePlay() async{
    setState(() {
      _isPlaying = !_isPlaying;
    });
    debugPrint("播放操作：$_isPlaying   url:${widget.voiceUrl}");
    if (_isPlaying) {
      _animationController.forward();
      // 开始播放音频的逻辑
      final duration = await player.setUrl(widget.voiceUrl);                 // Schemes: (https: | file: | asset: )
      player.play();
    } else {
      _animationController.reverse();
      // 暂停音频的逻辑
      player.pause();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10.0),
      ),
      elevation: 8.0,
      backgroundColor: Colors.white,
      child: Container(
        padding: EdgeInsets.all(32.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              width: 64.0,
              height: 64.0,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.blue,
              ),
              child: IconButton(
                icon: AnimatedIcon(
                  icon: AnimatedIcons.play_pause,
                  progress: _animationController,
                ),
                iconSize: 50.0,
                color: Colors.white,
                onPressed: _togglePlay,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
